﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace PinLayoutMVC.Models
{
    public class SurveyModel
    {
        public int ID { get; set; }
        public int QuestionID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public Boolean Published { get; set; }
        public DateTime CreationDate { get; set; }
        public List<QuestionModel> Questions { get; set; }

        private long SurveyType;
        private long SurveyState;

        public SurveyModel()
        {
            SurveyType = 0;
            SurveyState = 0;
            this.Questions = new List<QuestionModel>();
        }

        public void ValidateAndPublish()
        {
            Questions.ForEach(q => q.Validate());
            Questions.ForEach(q => validateChainQuestion(q));
            Published = !(Questions.Where(q => !string.IsNullOrEmpty(q.ValidationMessage)).Any());
        }

        private void validateChainQuestion(QuestionModel question)
        {
            foreach(AnswerModel answer in question.Answers.Where(a => !questionExists(a.LeadsToQuestion)))
            {
                question.AddValidationMessage("Question " + answer.LeadsToQuestion + " not found.");
            }
        }

        private Boolean questionExists(int questionNr)
        {
            return (questionNr == 0 || Questions.Where(q => q.Number == questionNr).Any());
        }


    }

    
}